#!/usr/bin/env python
#coding=UTF-8
'''
Created on 2010-11-7

@author: zarra
'''
import cv
from numpy import mat,abs,sqrt,log
def pow_ne1(v,x,y):
    return v if (x+y)%2 ==0 else -v

def show_image(image,title='image'):
    cv.NamedWindow(title)
    cv.ShowImage(title, image)

def copy_image(src):
 
    dst =  cv.CreateImage((src.width,src.height), src.depth, src.channels)
    cv.Copy(src, dst)
    return  dst

def matrix2image(m):
        height,width = m.shape
        dst =  cv.CreateImage((width,height), cv.IPL_DEPTH_8U, 1)
        i=j=0
        while i<height:
            j=0
            while j<width:
                dst[i,j]=abs(m[i,j])
                j+=1
            i+=1
        return dst
    
def image2matrix(image):
        height,width = image.height,image.width
        m=list()
        for i in range(height):
            row = [pow_ne1(image[i,j],i,j)  for j in range(width)]
            m.append(row)   
        return mat(m)
    
def safe_edge_get(image,x,y):
    '''返回图像中 (x,y)处像素的值,超出图像的位置返回图像对应边界的之 '''
    x=0 if x<0 else x
    y=0 if y<0 else y
    x=image.width-1  if x >= image.width  else x
    y=image.height-1 if y >= image.height else y
    
    return image[y,x] 

def amplitude_plot(m):
    '''画出2-D频谱图形'''
    height,width = m.shape
    result = cv.CreateImage(m.shape, cv.IPL_DEPTH_8U, 1)
    i=j=0
    while i<height:
        j=0
        while j<width:
            result[j,i] =abs(m[j,i])/result.height
            j+=1
        i+=1
            
    return result

class Question(object):
    def __init__(self,name,image_file,show_or_save='show'):
        self.name = name
        self.image = cv.LoadImage('../../data/%s'%image_file,iscolor=False)
        self.show_or_save = show_or_save
        self.display_method = {'show':self.show_image,
                               'save':self.save_image,}

    def save_image(self,image,title='image'):
        cv.SaveImage("../../output/%s_%s.jpg"%(self.name,title), image)
        
    def show_image(self,image,title='image'):
        t="%s_%s"%(self.name,title)
        cv.NamedWindow(t)
        cv.ShowImage(t, image)
        
    def display(self,image,title):
        return self.display_method[self.show_or_save](image,title)
    
    def action(self):
        '''虚函数,在派生类中重载,用以进行具体的图像处理过程'''
        pass
    
    def __call__(self):
        self.action()
        if self.show_or_save == 'show':
            cv.WaitKey()
        